package x.y.z;

public class Interview_1_5_OneAway {
    public boolean oneEditAway(String first, String second) {
        if (first.length() == second.length()) {
            return oneEditReplace(first, second);
        } else if (first.length() + 1 == second.length()) {
            return oneEditInsert(first, second);
        } else if (first.length() - 1 == second.length()) {
            return oneEditInsert(second, first);
        } else {
            return false;
        }
    }

    private boolean oneEditReplace(String first, String second) {
        boolean foundDifference = false;
        for (int i = 0; i < first.length(); i++) {
            if (first.charAt(i) != second.charAt(i)) {
                if (foundDifference) {
                    return false;
                }
                foundDifference = true;
            }
        }
        return true;
    }

    // insert a character into first to make second
    private boolean oneEditInsert(String first, String second) {
        int fstIndex = 0;
        int sndIndex = 0;
        while (fstIndex < first.length() && sndIndex < second.length()) {
            if (first.charAt(fstIndex) != second.charAt(sndIndex)) {
                if (fstIndex != sndIndex) {
                    return false;
                }
                sndIndex++;
            } else {
                fstIndex++;
                sndIndex++;
            }
        }
        return true;
    }
}
